package com.xxl.job.admin.api.service.impl;

import cn.hutool.json.JSONUtil;
import com.xxl.job.admin.api.model.CancelJobModel;
import com.xxl.job.admin.api.service.ApiAppService;
import com.xxl.job.admin.api.utils.StringUtils;
import com.xxl.job.admin.api.vo.ApiParam;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ApiAppServiceImpl implements ApiAppService {
    private static Logger logger = LoggerFactory.getLogger(ApiAppServiceImpl.class);

    @Resource
    public XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobService xxlJobService;
    @Resource
    private XxlJobInfoDao xxlJobInfoDao;

    @Override
    public ReturnT<?> handler(ApiParam param) {
        String opeType = param.getOpeType();
        String data = param.getData();

        logger.info("opeType={},data={}",opeType,data);

        ReturnT<?> res = null;
        //注册执行器
        if("registryGroup".equals(opeType)){
            res = registryGroup(data);
        }

        //添加任务
        if("addJob".equals(opeType)){
            res = addJob(data);
        }
        //取消任务
        if("cancelJob".equals(opeType)){
            res = cancelJob(data);
        }
        //开始任务
        if("startJob".equals(opeType)){
            res = startJob(data);
        }

        return res;
    }

    //注册执行器
    private ReturnT<?> registryGroup(String data){
        XxlJobGroup xxlJobGroup = JSONUtil.toBean(data, XxlJobGroup.class);
        XxlJobGroup load = xxlJobGroupDao.loadByAppName(xxlJobGroup.getAppname());
        if(Objects.nonNull(load)){
            List<String> registryList = xxlJobGroup.getRegistryList();
            if(Objects.nonNull(registryList) && !registryList.isEmpty()){
                //处理注册节点
                List<String> loadRegistryList = load.getRegistryList();
                if(Objects.nonNull(loadRegistryList) && !loadRegistryList.isEmpty()){
                    for (String ip : loadRegistryList) {
                        if(!registryList.contains(ip)){
                            registryList.add(ip);
                        }
                    }
                }

                String addressListStr = "";
                for (String item:registryList) {
                    addressListStr += item + ",";
                }
                addressListStr = addressListStr.substring(0, addressListStr.length()-1);
                load.setAddressList(addressListStr);
                load.setUpdateTime(new Date());
                xxlJobGroupDao.update(load);
            }
            //已经存在了
            return new ReturnT<>(load);
        }
        xxlJobGroup.setUpdateTime(new Date());
        int ret = xxlJobGroupDao.save(xxlJobGroup);
        load = xxlJobGroupDao.loadByAppName(xxlJobGroup.getAppname());
        return (ret>0)?new ReturnT<>(load):ReturnT.FAIL;
    }

    //添加任务
    private ReturnT<?> addJob(String data){
        XxlJobInfo jobInfo = JSONUtil.toBean(data, XxlJobInfo.class);

        String infoName = jobInfo.getInfoName();
        if(StringUtils.isBlank(infoName)){
            return ReturnT.FAIL;
        }
        //存在时，是否删除重建
        XxlJobInfo load = xxlJobInfoDao.loadByInfoName(infoName);
        if(Objects.nonNull(load)){
            if(jobInfo.isNewCreate()){
                if(load.getTriggerStatus() == 1){
                    xxlJobService.stop(load.getId());
                }
                xxlJobService.remove(load.getId());
            }else{
                return ReturnT.SUCCESS;
            }
        }

        ReturnT<String> res = xxlJobService.add(jobInfo);

        //是否立即开始
        if(jobInfo.isStart() && Objects.equals(res.getCode(),ReturnT.SUCCESS_CODE)){
            String content = res.getContent();
            xxlJobService.start(Integer.parseInt(content));
        }

        return res;
    }

    //取消任务
    private ReturnT<?> cancelJob(String data){
        CancelJobModel jobModel = JSONUtil.toBean(data, CancelJobModel.class);

        if(StringUtils.isBlank(jobModel.getInfoName())){
            return ReturnT.FAIL;
        }
        XxlJobInfo load = xxlJobInfoDao.loadByInfoName(jobModel.getInfoName());
        if(Objects.isNull(load)){
            return ReturnT.SUCCESS;
        }
        if(load.getTriggerStatus() == 1){
            xxlJobService.stop(load.getId());
        }
        if(jobModel.isDel()){
            xxlJobService.remove(load.getId());
        }
        return ReturnT.SUCCESS;
    }

    //开始一个任务
    private ReturnT<?> startJob(String data){
        if(StringUtils.isBlank(data)){
            return ReturnT.FAIL;
        }
        XxlJobInfo load = xxlJobInfoDao.loadByInfoName(data);
        if(Objects.isNull(load)){
            return ReturnT.FAIL;
        }
        if(load.getTriggerStatus() != 1){
            xxlJobService.start(load.getId());
        }
        return ReturnT.SUCCESS;
    }
}
